import React, { useState, useEffect, useRef } from 'react';
import { Button, Form, Input, Select, Col, Row, Tooltip, Table, Pagination, Modal, Radio, message } from 'antd';
import { SyncOutlined, SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined, ExclamationCircleOutlined, VerticalAlignBottomOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { getListAPI, delAPI, getDetailAPI, addAPI, putAPI } from '@/api/modules/equipment/jiaoyankey';
import { getDictsApi } from '@/api/modules/system/dictData';
import { download } from '@/api';
import { pageDelJump } from '@/utils';
import { IjiaoyankeyType, IjiaoyankeyDetailType } from '@/type/modules/equipment/jiaoyankey';
import ColorBtn from '@/components/ColorBtn';
import { hasPermi } from '@/utils/auth';
import { IdictType } from '@/type/modules/system/sysDictData';
import { GongzuoleixingTable2Select } from '@/views/equipment/gongzuoleixing';
import { ShebeileixingTableSelect } from '@/views/equipment/shebeileixing';
// 111
const JiaoyankeyTable = () => {
  const [queryForm] = Form.useForm();
  const [addEditForm] = Form.useForm();
  const { confirm } = Modal;

  // 分页
  const [queryParams, setQueryParams] = useState<IjiaoyankeyType>({ pageNum: 1, pageSize: 10 });
  // 列表数据
  const [dataList, setDataList] = useState({ count: 0, rows: [] as IjiaoyankeyDetailType[] });
  // table loading
  const [loading, setLoading] = useState(true);
  // 新增编辑 model显隐
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 新增编辑判断
  const [isAdd, setIsAdd] = useState(true);
  // 非单个禁用
  const [single, setSingle] = useState(true);
  // 非多个禁用
  const [multiple, setMultiple] = useState(true);
  // 保存table 选择的key
  const [selectKeys, setSelectKeys] = useState<React.Key[]>([]);
  //  table 后台使用的key
  const [rowKeys, setRowKeys] = useState('');
  // 控制搜索隐藏显示
  const [searchShow, setSearchShow] = useState(true);
  // 当前编辑的id
  const [currentId, setCurrentId] = useState<number>();

  useEffect(() => {
    try {
      const getDictsFn = async () => {};
      getDictsFn();
    } catch (error) {}
  }, []);

  // 查询列表
  const getList = async () => {
    try {
      const { data } = await getListAPI(queryParams);
      setDataList({ ...data.result });

      message.success('查询成功');
      setLoading(false);
    } catch (error) {}
  };

  useEffect(() => {
    getList();
  }, [queryParams]);

  // 搜索
  const searchQueryFn = () => {
    const form = queryForm.getFieldsValue();
    setQueryParams({
      pageNum: 1,
      pageSize: 10,
      ...form,
    });
  };

  // 重置
  const resetQueryFn = () => {
    queryForm.resetFields();
    setSelectKeys([]);
    setQueryParams({ pageNum: 1, pageSize: 10 });
  };

  // row-select
  const rowSelection = {
    selectedRowKeys: selectKeys,
    onChange: (selectedRowKeys: React.Key[]) => {
      if (!selectedRowKeys.length || selectedRowKeys.length > 1) {
        setSingle(true);
      } else {
        setSingle(false);
      }
      selectedRowKeys.length ? setMultiple(false) : setMultiple(true);
      setSelectKeys(selectedRowKeys);
      setRowKeys(selectedRowKeys.join(','));
    },
  };

  // 获取详情
  const handleEditForm = async (id: number) => {
    try {
      const { data } = await getDetailAPI(id);
      setCurrentId(id);
      setIsModalOpen(true);
      setIsAdd(false);
      addEditForm.setFieldsValue(data.result as unknown as IjiaoyankeyDetailType);
    } catch (error) {}
  };

  // 表单提交
  const handleFormFinish = async (values: IjiaoyankeyDetailType) => {
    let apiError = false;
    try {
      if (isAdd) {
        await addAPI({ ...values }).then(
          () => {
            message.success('新增成功');
          },
          () => (apiError = true),
        );
      } else {
        await putAPI({ ...values, tableId: currentId }).then(
          () => {
            message.success('修改成功');
          },
          () => (apiError = true),
        );
      }
    } catch (error) {}
    if (apiError) {
      return;
    }
    setIsModalOpen(false);
    addEditForm.resetFields();
    getList();
  };

  // 分页
  const onPagChange = async (pageNum: number, pageSize: number) => {
    const form = queryForm.getFieldsValue();   
    setQueryParams({ pageNum, pageSize,...form });
  };

  // 删除
  const delFn = (ids: string) => {
    confirm({
      icon: <ExclamationCircleOutlined />,
      content: `是否确认删除编号为"${ids}"的数据项？`,
      centered: true,
      async onOk() {
        try {
          const { data } = await delAPI(ids);
          message.success(data.message);
          pageDelJump(dataList.count, ids, queryParams, setQueryParams);
        } catch (error) {}
      },
    });
  };

  // table
  const columns = [
    {
      title: '编码',
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      render: (text, record, index) => index + 1, // 渲染序号
    },
    {
      title: '设备类型',
      dataIndex: 'fileType',
      key: 'fileType',
      align: 'center',
    },
    {
      title: '工作类型',
      dataIndex: 'workType',
      key: 'workType',
      align: 'center',
    },
    {
      title: '参数key',
      dataIndex: 'key',
      key: 'key',
      align: 'center',
    },
    {
      title: 'key的组名',
      dataIndex: 'keyGroupName',
      key: 'key',
      align: 'center',
    },
    {
      title: '操作',
      key: 'operation',
      align: 'center',
      fixed: 'right',
      render: (_: any, record: IjiaoyankeyDetailType) => (
        <div>
          <Button hidden={true || hasPermi('equipment:jiaoyankey:edit')} onClick={() => handleEditForm(record.tableId as number)} size="small" icon={<EditOutlined />} type="link">
            修改
          </Button>
          <Button hidden={hasPermi('equipment:jiaoyankey:remove')} size="small" icon={<DeleteOutlined />} type="link" onClick={() => delFn(String(record.tableId))}>
            删除
          </Button>
        </div>
      ),
    },
  ] as ColumnsType<IjiaoyankeyDetailType>;

  // table 数据源
  const tableData = dataList.rows;

  return (
    <div className="app-container">
      <Row gutter={16}>
        <Col span={24}>
          <Form form={queryForm} hidden={!searchShow} layout="inline" className="leno-search">
            <Form.Item label="设备类型" name="fileType">
              <ShebeileixingTableSelect style={{ width: 240 }} placeholder="请输入工作类型" allowClear onChange={searchQueryFn} />
            </Form.Item>
            <Form.Item label="工作类型" name="workType">
              <GongzuoleixingTable2Select style={{ width: 240 }} placeholder="请输入工作类型" allowClear onChange={searchQueryFn} />
            </Form.Item>
            <Form.Item label="参数key" name="key">
              <Input style={{ width: 240 }} placeholder="请输入参数key" allowClear onPressEnter={searchQueryFn} />
            </Form.Item>

            <Form.Item>
              <Button onClick={searchQueryFn} type="primary" icon={<SearchOutlined />}>
                搜索
              </Button>
            </Form.Item>
            <Form.Item>
              <Button onClick={resetQueryFn} icon={<SyncOutlined />}>
                重置
              </Button>
            </Form.Item>
          </Form>
          <Row gutter={16} className="mb10">
            <Col span={16} className="leno-btn">
              <Row gutter={8}>
                <Col>
                  <ColorBtn
                    hidden={hasPermi('equipment:jiaoyankey:add')}
                    icon={<PlusOutlined />}
                    onClick={() => {
                      setIsModalOpen(true);
                      setIsAdd(true);
                    }}
                  >
                    新增
                  </ColorBtn>
                </Col>
              </Row>
            </Col>
          </Row>
          <div className="leno-table">
            <Table columns={columns} dataSource={tableData} pagination={false} rowKey="tableId" size="middle" loading={loading}  />
            <Pagination className="pagination" onChange={onPagChange} total={dataList.count} showSizeChanger showQuickJumper current={queryParams.pageNum} showTotal={(total) => `共 ${total} 条`} />
          </div>

          {/* 添加 编辑 */}
          <Modal
            title={isAdd ? '添加校验key管理' : '编辑校验key管理'}
            open={isModalOpen}
            onOk={() => addEditForm.submit()}
            onCancel={() => {
              setIsModalOpen(false);

              addEditForm.resetFields();
            }}
          >
            <Form form={addEditForm} labelCol={{ span: 5 }} onFinish={handleFormFinish}>
              <Form.Item label="设备类型" name="fileType" hidden={false} rules={[{ required: true, message: '请输入设备类型!' }]}>
                <ShebeileixingTableSelect style={{ width: 240 }} placeholder="请选择设备类型" allowClear />
              </Form.Item>
              <Form.Item label="工作类型" name="workType" hidden={false} rules={[{ required: true, message: '请输入工作类型!' }]}>
                <GongzuoleixingTable2Select style={{ width: 240 }} placeholder="请选择工作类型" allowClear />
              </Form.Item>
              <Form.Item label="key的组名" name="key_group_name" hidden={false} rules={[{ required: true, message: '请输入key的组名!' }]}>
                <Input placeholder="请输入key的组名" />
              </Form.Item>
              <Form.Item label="参数key" name="key" hidden={false} rules={[{ required: true, message: '请输入参数key!' }]}>
                <Input placeholder="请输入参数key" />
              </Form.Item>
            </Form>
          </Modal>
        </Col>
      </Row>
    </div>
  );
};

export default JiaoyankeyTable;

let cacheData: any = []; // 缓存下拉数据，减少下组件请求接口的次数
// 当前列表的下拉选组件
export function JiaoyankeyTableSelect(props: any) {
  const { queryParams = {}, style = {} } = props;
  const [list, listSet] = useState([]);
  useEffect(() => {
    try {
      // if (cacheData.length > 0) {
      //   return listSet(cacheData)
      // }
      const init = async () => {
        const { data } = await getListAPI({ pageNum: 1, pageSize: 999999, ...queryParams });
        const listData: any = data.result.rows.map((item) => 
          // 需要自己改label和value的取值
           ({
            label: item.name,
            value: item.fileType,
          })
        );
        cacheData = listData;
        listSet(listData);
      };
      init();
    } catch (error) {}
  }, []);
  return <Select style={{ width: 240, ...style }} placeholder="请选择" options={list} {...props} />;
}
